#include <string>
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

#define LLIB_LIB_NAME_PREFIX    "llib"

#define BUF_SZ  1024
char    char_buf[BUF_SZ];

vector<string> split( const string& s, const string& delim =" " )
{
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

string getLlibFileName(const string &version_header_file_path, bool is_debug)
{
    ifstream header_file(version_header_file_path.c_str());
    if(!header_file.good()) {
        cout << "Failed to open version header file." << endl;
        return "";
    }

    string version_str = "";
    while( header_file.getline(char_buf, BUF_SZ) ) {
        string line(char_buf);
        vector<string> words = split(line);
        if((int)words.size() == 3 && words[0] == "#define" && words[1] == "DEFAULT_L_VERSION") {
            version_str = words[2];
            break;
        }
    }
    header_file.close();
    if(version_str == "") {
        cout << "Failed to fetch version info from header file." << endl;
        return "";
    }

    string res = string(LLIB_LIB_NAME_PREFIX) + "_" + version_str[0] + "." + version_str.substr(1) +
        (is_debug ? "_d" : "") + ".lib";
    return res;
}

int main(int argc, char** argv)
{
    system("pause");

    if(argc < 5) {
        cout << "Usage: llibMove [lversion.h file path] [original llib.lib file path] [target directory] [debug/release]" << endl;
        return -1;
    }

    string version_header_file_path(argv[1]);
    string debug_release(argv[4]);
    bool is_debug = debug_release == "debug";
    string target_file_name = getLlibFileName(version_header_file_path, is_debug);

    string llib_library_file_path(argv[2]);
    string target_directory(argv[3]);
    string copy_command = "copy " + llib_library_file_path + " " + target_directory + target_file_name + " /y";
    system(copy_command.c_str());
    cout << "Copy library file " << target_file_name << " successfully." << endl;

    return 0;
}

